<template>
  <!-- 弹窗最外层遮罩和容器结构 -->
  <div v-if="visible" class="custom-dialog-big-background">
    <div class="custom-dialog">
      <div class="dialog-backdrop" @click="closeDialog"></div>

      <div class="dialog-container">
        <!-- 弹窗头部：标题、关闭按钮 -->
        <div class="dialog-header">
          <slot name="header">
            <h3 class="dialog-title">{{ title }}</h3>
          </slot>
          <div class="buttons">
            <img src="../assets/img/module5/dialog/guanbi.png" @click="closeDialog" alt="关闭" class="button-icon" />
          </div>
        </div>

        <!-- 中间内容区：暂存库文件版本选择功能 -->
        <div class="dialog-content">
          <!-- 功能标题 -->
          <h4 class="step-title">暂存库文件版本选择</h4>

          <!-- 核心内容：文件列表（左）+ 版本详情（右） -->
          <div class="staging-library-container">
            <!-- 左侧：暂存库文件列表（带搜索） -->
            <div class="file-list-panel">
              <!-- 搜索与刷新 -->
              <div class="search-bar">
                <el-input v-model="searchFileName" placeholder="搜索文件名" clearable size="small" 
                  @clear="fetchStagingFiles" @keyup.enter="fetchStagingFiles"
                  style="width: 75%;">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button size="mini" class="refresh-btn" @click="fetchStagingFiles" style="margin-left: 8px;">
                  <i class="el-icon-refresh"></i> 搜索
                </el-button>
              </div>

              <!-- 文件列表表格 -->
              <el-table ref="fileTable" :data="stagingFileList" tooltip-effect="dark" class="container-scoll file-table"
                @row-click="handleFileSelect" :highlight-current-row="true" @selection-change="handleFileSelection"
                :current-row-key="currentSelectedFile && currentSelectedFile.id"
                style="width: 100%; height: calc(100% - 40px);">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="文件名称" prop="title" width="220" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="file-name-wrapper">
                      <i :class="getFileIcon(scope.row.pdfUrl)" class="file-icon"></i>
                      <span>{{ scope.row.title }}</span>
                    </div>
                  </template>
                </el-table-column>
                <!-- 新增：最新版本号列 -->
                <el-table-column label="最新版本号" width="120">
                  <template #default="scope">
                    <span class="latest-version">
                      V{{ 
                        (scope.row.versions.find(v => v.isLatest) || scope.row.versions[0]) && 
                        (scope.row.versions.find(v => v.isLatest) || scope.row.versions[0]).versionNumber 
                        || '未知' 
                      }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="文件类型" width="120">
                  <template #default="scope">
                    <span>{{ getFileType(scope.row.pdfUrl) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="版本数量" width="100">
                  <template #default="scope">
                    <span class="version-count" :class="scope.row.versions.length > 1 ? 'multiple-version' : ''">
                      {{ scope.row.versions.length }} 个
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="最新传入时间" prop="publicationTime" width="180"></el-table-column>
                <el-table-column label="信息来源" prop="informationSources" width="120"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="当前状态" width="120">
                  <template #default="scope">
                    <el-tag :type="scope.row && scope.row.importStatus === 0 ? 'info' : 'success'" size="mini">
                      {{ scope.row && scope.row.importStatus === 0 ? '待导入' : '已导入' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 右侧：当前文件基础信息 -->
            <div class="version-detail-panel">
              <!-- 无文件选中时的提示 -->
              <div v-if="!currentSelectedFile" class="empty-tip">
                <i class="el-icon-file-text"></i>
                <p>请从左侧暂存库选择文件（支持多选）</p>
              </div>

              <!-- 有文件选中时的内容 -->
              <div v-else class="version-content">
                <div class="file-basic-info">
                  <h5 class="info-title">文件基础信息</h5>
                  <div class="info-row">
                    <span class="info-label">文件名称：</span>
                    <span class="info-value">{{ currentSelectedFile.title }}</span>
                  </div>
                  <div class="info-row">
                    <span class="info-label">最新版本：</span>
                    <span class="info-value">
                      V{{ 
                        (currentSelectedFile.versions.find(v => v.isLatest) || currentSelectedFile.versions[0]) &&
                        (currentSelectedFile.versions.find(v => v.isLatest) || currentSelectedFile.versions[0]).versionNumber 
                        || '未知' 
                      }}
                    </span>
                  </div>
                  <div class="info-row">
                    <span class="info-label">最新传入时间：</span>
                    <span class="info-value">{{ currentSelectedFile.publicationTime }}</span>
                  </div>
                  <div class="info-row">
                    <span class="info-label">暂存状态：</span>
                    <span class="info-value">
                      <el-tag :type="currentSelectedFile && currentSelectedFile.importStatus === 0 ? 'info' : 'success'"
                        size="mini">
                        {{ currentSelectedFile && currentSelectedFile.importStatus === 0 ? '待导入' : '已导入' }}
                      </el-tag>
                    </span>
                  </div>
                </div>

                <!-- 多选文件数量提示 -->
                <div v-if="selectedFiles.length > 0" class="selected-version-tip">
                  <i class="el-icon-check-circle"></i>
                  已选择 {{ selectedFiles.length }} 个文件（将导入各文件最新版本）
                </div>
              </div>
            </div>
          </div>

          <!-- 底部操作按钮 -->
          <div class="buttonWapper">
            <button class="diaButton" @click="closeDialog">取消</button>
            <button 
              class="diaButton" 
              @click="handleConfirmImport" 
              :disabled="selectedFiles.length === 0 || selectedFiles.every(file => file.importStatus === 1)"
            >
              {{ selectedFiles.length === 0 ? '请选择文件' : '确认导入选中文件' }}
            </button>
          </div>
        </div>

        <!-- 弹窗底部标识图 -->
        <div class="dialog-footer">
          <img src="../assets/img/module5/dialog/dialogicon3.png" class="img-foot" alt="弹窗底部标识" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

// 基础API路径
const baseApi = process.env.NODE_ENV === 'production'
  ? '/api'
  : process.env.VUE_APP_REMOTE_API_MODULE1;

export default {
  name: "CustomDialogFileAdd",
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    title: {
      type: String,
      default: "暂存库文件导入"
    },
    width: {
      type: String,
      default: '80%'
    },
    height: {
      type: String,
      default: '600px'
    }
  },
  data() {
    return {
      searchFileName: '', // 文件名搜索关键词
      stagingFileList: [], // 暂存库文件列表（筛选后）
      currentSelectedFile: null, // 当前选中的文件
      selectedFiles: [], // 存储多选的文件列表
      rawStagingFileList: [], // 存储原始文件列表（用于搜索筛选）
    };
  },
  watch: {
    // 监听visible变化，打开弹窗时加载数据，关闭时重置
    visible(newVal, oldVal) {
      if (newVal && !oldVal) {
        this.fetchStagingFiles();
      }
      if (!newVal) {
        this.resetDialog();
      }
    }
  },
  methods: {
    /**
     * 调用接口获取暂存库文件列表
     */
    async fetchStagingFiles() {
      try {
        const loading = this.$loading({
          lock: true,
          text: '加载暂存库文件中...',
          target: '.file-list-panel',
          background: 'rgba(0, 0, 0, 0.3)'
        });

        const response = await axios.get(`${baseApi}/admin/airspaceNormsAndConstraints/getImportList`);

        if (response.data.code === 0 && Array.isArray(response.data.data)) {
          // 存储全部格式化后的数据
          this.rawStagingFileList = this.formatFileData(response.data.data);

          // 根据搜索关键词筛选
          const keyword = this.searchFileName.trim().toLowerCase();
          this.stagingFileList = keyword
            ? this.rawStagingFileList.filter(file => 
                file.title.toLowerCase().includes(keyword)
              )
            : [...this.rawStagingFileList];
        } else {
          this.stagingFileList = [];
          this.rawStagingFileList = [];
          this.$message.warning("未获取到暂存库文件数据");
        }

        loading.close();
      } catch (error) {
        console.error("暂存库文件加载失败：", error);
        this.stagingFileList = [];
        this.rawStagingFileList = [];
        if (this.visible) {
          this.$message.error("数据加载失败，请检查接口连接或重试");
        }
      }
    },

    /**
     * 格式化接口数据：按文件分组，构建版本列表
     */
    formatFileData(rawData) {
      const fileGroup = {};
      rawData.forEach(item => {
        const fileKey = item.title;
        if (!fileGroup[fileKey]) {
          fileGroup[fileKey] = {
            id: item.id,
            title: item.title,
            publicationTime: item.publicationTime,
            informationCategory: item.informationCategory,
            informationSources: item.informationSources,
            pdfUrl: item.pdfUrl,
            importStatus: item.importStatus,
            versions: []
          };
        }
        fileGroup[fileKey].versions.push({
          versionNumber: item.versionNumber,
          isLatest: item.isLatest,
          parentVersionId: item.parentVersionId,
          publicationTime: item.publicationTime,
          usingStandards: item.usingStandards,
          constraintInformation: item.constraintInformation,
          pdfUrl: item.pdfUrl,
          normsConstraintsId: item.normsConstraintsId,
          id: item.id
        });
      });

      // 按最新传入时间倒序排序
      return Object.values(fileGroup).sort((a, b) => {
        return new Date(b.publicationTime) - new Date(a.publicationTime);
      });
    },

    /**
     * 弹窗关闭时重置状态
     */
    resetDialog() {
      this.searchFileName = '';
      this.currentSelectedFile = null;
      this.selectedFiles = [];
      if (this.$refs.fileTable) this.$refs.fileTable.clearSelection();
    },

    /**
     * 获取文件类型
     */
    getFileType(pdfUrl) {
      return pdfUrl ? 'PDF文件' : '未知类型';
    },

    /**
     * 获取文件图标
     */
    getFileIcon(pdfUrl) {
      return pdfUrl ? 'el-icon-file-pdf' : 'el-icon-file';
    },

    /**
     * 转换信息类别
     */
    getInformationCategory(categoryCode) {
      const categoryMap = {
        0: '空域基础类',
        1: '运营管理类',
        2: '安全规范类'
      };
      return categoryMap[categoryCode] || `未知类别(${categoryCode})`;
    },

    /**
     * 处理文件多选
     */
    handleFileSelection(val) {
      this.selectedFiles = val;
    },

    /**
     * 选中左侧文件
     */
    handleFileSelect(row) {
      this.currentSelectedFile = row;
    },

    /**
     * 确认导入选中文件（批量导入最新版本）
     */
    async handleConfirmImport() {
      // 过滤已导入的文件
      const pendingFiles = this.selectedFiles.filter(file => file.importStatus === 0);
      if (pendingFiles.length === 0) {
        this.$message.info("选中文件均已导入，无需重复操作");
        return;
      }

      // 获取每个文件的最新版本ID
      const importIds = pendingFiles.map(file => {
        const latestVersion = file.versions.find(v => v.isLatest) || file.versions[0];
        return latestVersion.id;
      });

      // 显示加载动画
      const loading = this.$loading({
        lock: true,
        text: `正在导入 ${pendingFiles.length} 个文件的最新版本...`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 调用批量导入接口
        const response = await axios.post(
          `${baseApi}/admin/airspaceNormsAndConstraints/batchImport`,
          importIds
        );

        if (response.data.code === 0) {
          this.$message.success(`成功导入 ${pendingFiles.length} 个文件（均为最新版本）`);
          // 更新本地文件状态
          pendingFiles.forEach(file => {
            file.importStatus = 1;
          });
          this.closeDialog();
          // 向父组件传递导入成功的信息
          this.$emit('import-success', pendingFiles.map(file => ({
            fileId: file.id,
            latestVersion: (file.versions.find(v => v.isLatest) || file.versions[0]).versionNumber,
            title: file.title
          })));
        } else {
          throw new Error(response.data.message || '导入接口返回异常');
        }
      } catch (error) {
        console.error("文件导入失败：", error);
        this.$message.error(`导入失败：${error.message || '网络异常或接口错误'}`);
      } finally {
        loading.close();
      }
    },

    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.resetDialog();
      this.$emit("update:visible", false);
    }
  }
};
</script>

<style scoped>
/* 弹窗基础样式 */
.custom-dialog-big-background {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}

.custom-dialog {
  position: relative;
  width: 80%;
  height: v-bind(height);
  background: url("../assets/img/module5/dialog/container.png") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 20px;
  overflow: hidden;
}

.dialog-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}

.dialog-container {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 弹窗头部 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.dialog-title {
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.buttons .button-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

/* 内容区标题 */
.step-title {
  color: #409EFF;
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

/* 左右分栏容器 */
.staging-library-container {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

/* 左侧文件列表面板 */
.file-list-panel {
  width: 45%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: rgba(0, 16, 31, 0.6);
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.refresh-btn {
  background: #409EFF;
  color: #fff;
}

.file-table {
  background: rgba(0, 20, 40, 0.8);
  color: #fff;
}

.file-table th {
  background: rgba(0, 30, 60, 0.9) !important;
  color: #E5E6EB !important;
}

.file-table td {
  color: #E5E6EB !important;
}

.file-name-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  font-size: 18px;
  color: #FF4D4F;
}

.version-count {
  color: #E5E6EB;
}

.multiple-version {
  color: #409EFF;
  font-weight: 500;
}

.latest-version {
  color: #67C23A;
  font-weight: 500;
}

/* 右侧版本详情面板 */
.version-detail-panel {
  width: 55%;
  height: 100%;
  background: rgba(0, 16, 31, 0.6);
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  color: #909399;
}

.empty-tip i {
  font-size: 48px;
  margin-bottom: 15px;
}

.version-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.file-basic-info {
  background: rgba(0, 20, 40, 0.8);
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 15px;
}

.info-title {
  color: #409EFF;
  font-size: 15px;
  font-weight: 500;
  margin: 0 0 10px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(64, 158, 255, 0.3);
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  line-height: 1.5;
}

.info-label {
  width: 100px;
  color: #909399;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #E5E6EB;
  font-size: 14px;
}

/* 已选文件提示 */
.selected-version-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 15px;
  padding: 10px 12px;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid #409EFF;
  border-radius: 4px;
  color: #409EFF;
  font-size: 14px;
}

/* 底部按钮区域 */
.buttonWapper {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 15px;
}

.diaButton {
  padding: 8px 24px;
  background: linear-gradient(180deg, #409EFF 0%, #1E88E5 100%);
  border: none;
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.diaButton:disabled {
  background: linear-gradient(180deg, #909399 0%, #606266 100%);
  cursor: not-allowed;
  opacity: 0.7;
}

.diaButton:first-child {
  background: linear-gradient(180deg, #909399 0%, #606266 100%);
}

/* 弹窗底部图标 */
.dialog-footer {
  position: absolute;
  bottom: 10px;
  right: 10px;
  z-index: 3;
}

.img-foot {
  width: 80px;
  height: 80px;
}

/* 滚动条样式优化 */
.container-scoll::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.container-scoll::-webkit-scrollbar-track {
  background: rgba(0, 20, 40, 0.5);
  border-radius: 3px;
}

.container-scoll::-webkit-scrollbar-thumb {
  background: #409EFF;
  border-radius: 3px;
}

.container-scoll::-webkit-scrollbar-thumb:hover {
  background: #66b1ff;
}
</style>
